<template>
    <div class="wrapper">
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }"
                >首页
            </el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>


        <!-- 卡片区域 -->
        <el-card>
            <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-input placeholder="请输入用户名" v-model="input">
                        <el-button
                            slot="append"
                            icon="el-icon-search"
                            @click="getUser"
                        ></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="dialogVisible = true"
                        >添加用户</el-button
                    >
                </el-col>
            </el-row>

            <!-- 添加用户面板 -->
            <el-dialog
                title="添加用户"
                :visible.sync="dialogVisible"
                width="30%"
            >
                <!-- 添加用户弹出框 -->
                <el-form
                    label-width="80px"
                    :model="from"
                    :rules="rules"
                    status-icon
                    ref="ruleForm"
                >
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="from.username" type="text"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input
                            type="password"
                            v-model="from.password"
                            autocomplete="off"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input type="email" v-model="from.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input
                            type="tel"
                            v-model.number="from.mobile"
                        ></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary"  @click="submitForm(from);dialogVisible = false">确 定</el-button
                >
                </span>
            </el-dialog>

            <!-- 渲染用户列表 -->
            <el-table :data="userList" style="width: 100%" border>
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <!-- 使用作用域插槽 -->
                    <template v-slot="scope">
                        <el-switch
                            v-model="scope.row.mg_state"
                            active-color="#13ce66"
                            inactive-color="#ccc"
                            @change='modifyUserState(scope.row.id, scope.row.mg_state)'>
                        </el-switch>
                    </template>
                </el-table-column>

                <!-- 操作区域 -->
                <el-table-column label="操作" width="200">
                    <template v-slot="scope">
                        <!-- {{scope.row}} -->
                        <el-row>
                            <el-tooltip
                                class="item"
                                effect="dark"
                                content="修改"
                                placement="top-start"
                            >
                                <el-button
                                    size="small"
                                    type="primary"
                                    class="el-icon-edit"
                                    @click='dialogVisibleModify = true; modifyUserData(scope.row)'
                                ></el-button>
                            </el-tooltip>
                            <el-tooltip
                                class="item"
                                effect="dark"
                                content="删除"
                                placement="top-start"
                            >
                                <el-button
                                    size="small"
                                    type="danger"
                                    class="el-icon-delete"
                                    @click='deleteUser(scope.row.id)'
                                ></el-button>
                            </el-tooltip>
                            <el-tooltip
                                class="item"
                                effect="dark"
                                content="分配角色"
                                placement="top-start"
                            >
                                <el-button
                                    size="small"
                                    type="warning"
                                    class="el-icon-s-tools"
                                    @click='assignRolesStat = true;updateRolesData(scope.row)'
                                ></el-button>
                            </el-tooltip>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 修改用户信息面板 -->
            <el-dialog
                title="修改用户信息"
                :visible.sync="dialogVisibleModify"
                width="30%">
                <!-- 修改用户信息表单 -->
                <el-form
                    label-width="80px"
                    :model="modifyUserInfo"
                    :rules="rules"
                    status-icon
                    ref="modifyFrom"
                    
                >
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="modifyUserInfo.username" type="text" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input type="email" v-model="modifyUserInfo.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input
                            type="tel"
                            v-model.number="modifyUserInfo.mobile"
                        ></el-input>
                    </el-form-item>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisibleModify = false">取 消</el-button>
                    <el-button type="primary" @click="dialogVisibleModify = false;sendModifyUserData()">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 分配角色信息面板 -->
            <el-dialog
                title="分配角色"
                :visible.sync="assignRolesStat"
                width="30%">
                <p>当前用户名：{{userRolesData.name}}</p>
                <p class="rolesStyle">用户角色：{{userRolesData.role}}</p>
                <el-select v-model="userRolesData.select" placeholder="请选择用户角色">
                    <el-option v-for="value in userRolesData.data" :label="value.roleName" :value="value.id" :key='value.id'></el-option>
                </el-select>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="assignRolesStat = false">取 消</el-button>
                    <el-button type="primary" @click="assignRolesStat = false;setUserRoles()">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 底部分页部分 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="100"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
    </div>
</template>

<script>
export default {
    name: "Users",
    data() {
        return {
            input: "",
            // 获取yoghurt参数
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: '5'
            },
            // 用户列表数据
            userList: [],
            // 用户总数
            total: null,
            // 添加用户面板状态
            dialogVisible: false,
            // 修改用户面板状态
            dialogVisibleModify: false,
            // 分配角色面板状态
            assignRolesStat: false,
            // 添加用户表单数据
            from: {
                username: '',
                password: '',
                email: '',
                mobile: null
            },
            // 添加用户表单校验
            rules: {
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                email: [
                    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                mobile: [
                    {required: true, message: '请输入手机号', trigger: 'blur'},
                    { type: 'number', message: '请输入正确的手机号码', trigger: 'blur'}
                ]
            },
            // 修改用户信息
            modifyUserInfo: {
                username: '',
                email: '',
                mobile: null,
                id: null
            },
            // 用户角色数据
            userRolesData: {
                data: [],
                select: '',
                userId: null,
                name: '',
                role: ''
            }
        };
    },
    methods: {
        // 获取用户列表
        async getUser() {
            this.queryInfo.query = this.input;
            let {data: res} = await this.$http.get('/users', {
                params: this.queryInfo
            })
            if(res.meta.status !== 200) return this.$message.error('获取用户列表失败');
            this.userList = res.data.users;
            this.total = res.data.total;
            this.input = '';
        },
        // 控制添加用户的关闭和取消
        handleClose(done) {
            this.$confirm('确认关闭？')
            .then(() => {
                done();
            }).catch(() => {});
        },
        // 添加用户校验
        submitForm({username, password, email, mobile}) {
            console.log(username, password, email, mobile)
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    let {data:res} = await this.$http.post('/users', {
                        username,
                        password,
                        email,
                        mobile
                    })
                    if(res.meta.msg === '用户名已存在') {
                        this.$message.info(res.meta.msg)
                        return 
                    }

                    if(res.meta.status === 201) {
                        this.getUser()
                        this.$message.success('用户添加成功')
                    }
                } else {
                    this.$message.error('信息输入有误')
                    return false;
                }
            });
        },
        // 修改用户信息
        modifyUserData({id, username, email, mobile}) {
            this.modifyUserInfo.username = username;
            this.modifyUserInfo.email = email;
            this.modifyUserInfo.id = id;

            mobile = Number(mobile);
            if(mobile) {
                this.modifyUserInfo.mobile = mobile;
            }
            
        },
        // 提交用户修改信息
        sendModifyUserData() {
            // 提交修改信息
            this.$refs.modifyFrom.validate(valid => {
                if(!valid) return this.$message.error('用户信息格式有误，请输入正确的格式');
                let id = Number(this.modifyUserInfo.id);
                this.$http.put('users/' + id, {
                    email: this.modifyUserInfo.email,
                    mobile: this.modifyUserInfo.mobile
                }).then(() => {
                    this.getUser();
                })
            })
            
            
        },
        // 修改用户状态
        async modifyUserState(id, state) {
            let {data: res} = await this.$http.put(`/users/${id}/state/${state}`);
            if(res.meta.status === 200) {
                this.$message.success('状态修改成功')
            }else {
                this.$message.error('状态修改失败')
            }
        },
        // 删除单个用户
        async deleteUser(id) {
            await this.$http.delete(`/users/${id}`);
            this.$message.success('删除用户成功');
            this.getUser();
        },
        // 获取用户角色
        async getUserRoles() {
            try{
                let {data:res} = await this.$http.get('/roles');
                if(res.meta.status === 200) {
                    this.userRolesData.data = res.data;
                }
            }catch(error) {
                console.log(`获取用户角色错误: ${error.message}`)
            }
        },
        // 设置用户角色
        updateRolesData({id, role_name, username}) {
            this.userRolesData.userId = id;
            this.userRolesData.role = role_name;
            this.userRolesData.name = username;
        },
        setUserRoles() {
            this.$http.put(`users/${this.userRolesData.userId}/role`, {
                rid: this.userRolesData.select
            }).then(res => {
                if(res.data.meta.status === 200) {
                    this.getUser();
                    this.$message.success('分配角色成功');
                }
            }).catch(error => {
                console.log(`设置用户角色错误信息：${error.message}`)
            })
        },

        // 分页功能
        handleSizeChange(value) {
            this.queryInfo.pagesize = value;
            this.getUser();
        },
        handleCurrentChange(value) {
            this.queryInfo.pagenum = value;
            this.getUser();
        }
    },
    created() {
        // 设置请求拦截器
        // this.$http.interceptors.request.use(config => {
        //     config.headers.Authorization = sessionStorage.getItem('token');
        //     return config;
        // },error => {
        //     console.log('请求拦截器设置失败')
        //     return Promise.reject(error);
        // });
        // 调用获取用户列表方法
        this.getUser();
        // 调用获取用户列表
        this.getUserRoles();
    },
};
</script>

<style lang='less' scoped>
    .wrapper {
        width: 100%;
        height: 0px;
        padding: 10px 20px;
        box-sizing: border-box;
        line-height: 20px;
        .rolesStyle{
            margin: 15px 0;
        }
        .el-pagination{
            margin-top: 15px;
        }
    }
</style>
